package test2;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    public String serverIp;
    public int serverPort;
    public DatagramSocket socket = null;
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        while(true){
            System.out.print("->");
            Scanner scanner = new Scanner(System.in);
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(this.serverIp),this.serverPort);
            socket.send(requestPacket);
            DatagramPacket resposnePacket = new DatagramPacket(new byte[4096],0,4096);
            socket.receive(resposnePacket);
            String response = new String(resposnePacket.getData(),0,resposnePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient c = new UdpEchoClient("127.0.0.1",9090);
        c.start();
    }
}
